package com.rui.study.algorithm.L_二叉搜索树_3后序遍历;

import com.rui.study.algorithm.TreeNode;

import java.util.Stack;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2019-01-23 09:21
 **/
public class PostOrderTraversing_未完成 {

    public String postOrderTraversing(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        StringBuffer buf = new StringBuffer("[");
        TreeNode p = root;
        while (p != null || !stack.empty()) {
            if (p != null) {
                stack.push(p);
                p = p.left;
            } else {
                TreeNode tmp = stack.pop();
                buf.append(tmp.val + ",");
            }
        }

        buf.deleteCharAt(buf.lastIndexOf(","));
        buf.append("]");
        return buf.toString();
    }

    public static void main(String[] args) {

        // 构建二叉搜索树
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        TreeNode node7 = new TreeNode(7);

        TreeNode root = node5;
        root.left = node3;
        root.right = node6;
        node3.left = node2;
        node3.right = node4;
        node6.right = node7;


        long start = System.currentTimeMillis();
        PostOrderTraversing_未完成 in = new PostOrderTraversing_未完成();
        String result = in.postOrderTraversing(root);
        long end = System.currentTimeMillis();
        System.out.println("后序遍历：" + result + ", 耗时[" + (end - start) + "ms]");
    }
}
